import { Missile } from '../entities/Missile.js';
import { EntitySystem } from './EntitySystem.js';
import { GameConfig, MissileType } from '../config/GameConfig.js';

// 攻击波次配置
interface AttackWave {
    waveNumber: number;
    missiles: Array<{
        type: MissileType;
        count: number;
        interval: number; // 发射间隔（毫秒）
        delay: number;    // 波次延迟（毫秒）
    }>;
    name: string;
    description: string;
}

export class AttackSystem {
    private entitySystem: EntitySystem;
    private currentWave: number = 0;
    private isWaveActive: boolean = false;
    private waveTimer: number = 0;
    private missileQueue: Array<{
        type: MissileType;
        launchTime: number;
        targetX: number;
        targetY: number;
    }> = [];
    private totalMissilesLaunched: number = 0;
    private activeMissiles: Missile[] = [];
    
    // 事件回调
    public onWaveStart: ((wave: number, name: string) => void) | null = null;
    public onWaveEnd: ((wave: number) => void) | null = null;
    public onMissileLaunch: ((missile: Missile) => void) | null = null;
    public onMissileDestroyed: ((missile: Missile, intercepted: boolean) => void) | null = null;

    constructor(entitySystem: EntitySystem) {
        this.entitySystem = entitySystem;
    }

    async init(): Promise<void> {
        console.log('🚀 初始化攻击系统...');
        console.log('✅ 攻击系统初始化完成');
    }

    update(deltaTime: number): void {
        this.waveTimer += deltaTime;
        
        // 处理导弹发射队列
        this.processLaunchQueue();
        
        // 更新活跃导弹列表
        this.updateActiveMissiles();
        
        // 检查波次状态
        this.checkWaveStatus();
    }

    private processLaunchQueue(): void {
        for (let i = this.missileQueue.length - 1; i >= 0; i--) {
            const queuedMissile = this.missileQueue[i];
            
            if (this.waveTimer >= queuedMissile.launchTime) {
                this.launchMissile(
                    queuedMissile.type,
                    queuedMissile.targetX,
                    queuedMissile.targetY
                );
                this.missileQueue.splice(i, 1);
            }
        }
    }

    private updateActiveMissiles(): void {
        this.activeMissiles = this.entitySystem.getEntitiesOfType(Missile).filter(missile => missile.active);
    }

    private checkWaveStatus(): void {
        if (this.isWaveActive && this.missileQueue.length === 0 && this.activeMissiles.length === 0) {
            // 当前波次结束
            this.endCurrentWave();
        }
    }

    private launchMissile(type: MissileType, targetX: number, targetY: number): void {
        const missileId = `missile_${this.totalMissilesLaunched++}`;
        
        // 从伊朗区域的随机位置发射
        const launchX = Math.random() * (GameConfig.IRAN_AREA_WIDTH - 20) + 10;
        const launchY = Math.random() * (GameConfig.CANVAS_HEIGHT - 100) + 50;
        
        const missile = new Missile(missileId, type, launchX, launchY, targetX, targetY);
        
        this.entitySystem.addEntity(missile);
        this.activeMissiles.push(missile);
        
        console.log(`🚀 发射导弹: ${type} from (${launchX.toFixed(0)}, ${launchY.toFixed(0)}) to (${targetX.toFixed(0)}, ${targetY.toFixed(0)})`);
        
        if (this.onMissileLaunch) {
            this.onMissileLaunch(missile);
        }
    }

    // 开始指定波次
    public startWave(waveNumber: number): void {
        if (this.isWaveActive) {
            console.warn('⚠️ 当前波次尚未结束，无法开始新波次');
            return;
        }

        const wave = this.getWaveConfig(waveNumber);
        if (!wave) {
            console.error(`❌ 找不到波次 ${waveNumber} 的配置`);
            return;
        }

        console.log(`🌊 开始波次 ${waveNumber}: ${wave.name}`);
        
        this.currentWave = waveNumber;
        this.isWaveActive = true;
        this.waveTimer = 0;
        this.missileQueue = [];
        
        // 生成导弹发射队列
        this.generateLaunchQueue(wave);
        
        if (this.onWaveStart) {
            this.onWaveStart(waveNumber, wave.name);
        }
    }

    private generateLaunchQueue(wave: AttackWave): void {
        let currentTime = 0;
        
        wave.missiles.forEach(missileGroup => {
            currentTime += missileGroup.delay;
            
            for (let i = 0; i < missileGroup.count; i++) {
                const launchTime = currentTime + i * missileGroup.interval;
                
                // 随机选择目标
                const target = this.selectRandomTarget();
                
                this.missileQueue.push({
                    type: missileGroup.type,
                    launchTime: launchTime,
                    targetX: target.x,
                    targetY: target.y
                });
            }
        });
        
        // 按发射时间排序
        this.missileQueue.sort((a, b) => a.launchTime - b.launchTime);
        
        console.log(`📋 生成了 ${this.missileQueue.length} 枚导弹的发射队列`);
    }

    private selectRandomTarget(): { x: number; y: number } {
        // 🎯 修复：使用与EntitySystem中建筑物相匹配的实际坐标
        const targets = [
            { x: 1050, y: 300, weight: 3 }, // 政府大楼（高优先级） - 与EntitySystem匹配
            { x: 1100, y: 500, weight: 2 }, // 机场 - 与EntitySystem匹配
            { x: 950, y: 600, weight: 2 },  // 港口 - 与EntitySystem匹配
            { x: 1000, y: 450, weight: 2 }, // 住宅区 - 与EntitySystem匹配
            { x: 1150, y: 350, weight: 2 }, // 军事基地 - 与EntitySystem匹配
            { x: 1080, y: 200, weight: 1 }, // 额外目标点1
            { x: 980, y: 400, weight: 1 },  // 额外目标点2
        ];
        
        // 加权随机选择
        const totalWeight = targets.reduce((sum, target) => sum + target.weight, 0);
        let random = Math.random() * totalWeight;
        
        for (const target of targets) {
            random -= target.weight;
            if (random <= 0) {
                // 添加一些随机偏移
                return {
                    x: target.x + (Math.random() - 0.5) * 50,
                    y: target.y + (Math.random() - 0.5) * 50
                };
            }
        }
        
        // 备选方案：如果权重计算失败，返回政府大楼坐标
        return {
            x: 1050 + (Math.random() - 0.5) * 30,
            y: 300 + (Math.random() - 0.5) * 30
        };
    }

    private endCurrentWave(): void {
        console.log(`🏁 波次 ${this.currentWave} 结束`);
        
        this.isWaveActive = false;
        
        if (this.onWaveEnd) {
            this.onWaveEnd(this.currentWave);
        }
    }

    private getWaveConfig(waveNumber: number): AttackWave | null {
        const waveConfigs: AttackWave[] = [
            // 第1关：铁穹初试 (教学关卡)
            {
                waveNumber: 1,
                name: "初试锋芒",
                description: "少量基础导弹测试防御",
                missiles: [
                    { type: 'FATEH_110', count: 3, interval: 5000, delay: 0 },
                    { type: 'QIAM_1', count: 2, interval: 3000, delay: 15000 }
                ]
            },
            
            // 第2关：多层防御测试
            {
                waveNumber: 2,
                name: "混合威胁",
                description: "多种导弹类型的组合攻击",
                missiles: [
                    { type: 'FATEH_110', count: 5, interval: 3000, delay: 0 },
                    { type: 'SHAHED_136', count: 3, interval: 8000, delay: 10000 },
                    { type: 'QIAM_1', count: 4, interval: 4000, delay: 25000 }
                ]
            },
            
            // 第3关：中等威胁
            {
                waveNumber: 3,
                name: "威胁升级",
                description: "包含中程导弹的攻击",
                missiles: [
                    { type: 'QIAM_1', count: 4, interval: 2500, delay: 0 },
                    { type: 'SHAHAB_3', count: 2, interval: 15000, delay: 12000 },
                    { type: 'ZELZAL_2', count: 3, interval: 8000, delay: 20000 },
                    { type: 'SHAHED_136', count: 5, interval: 6000, delay: 35000 }
                ]
            },
            
            // 第4关：高强度攻击
            {
                waveNumber: 4,
                name: "饱和攻击",
                description: "大规模导弹齐射",
                missiles: [
                    { type: 'FATEH_110', count: 8, interval: 2000, delay: 0 },
                    { type: 'QIAM_1', count: 6, interval: 1500, delay: 5000 },
                    { type: 'SHAHED_136', count: 8, interval: 4000, delay: 15000 },
                    { type: 'SHAHAB_3', count: 3, interval: 12000, delay: 25000 },
                    { type: 'ZELZAL_2', count: 4, interval: 8000, delay: 30000 }
                ]
            },
            
            // 第5关：超音速危机
            {
                waveNumber: 5,
                name: "超音速威胁",
                description: "首次出现超音速导弹",
                missiles: [
                    { type: 'QIAM_1', count: 6, interval: 2000, delay: 0 },
                    { type: 'FATEH_110', count: 4, interval: 3000, delay: 8000 },
                    { type: 'FATTAH_2', count: 1, interval: 20000, delay: 20000 }, // 超音速导弹
                    { type: 'SHAHED_136', count: 6, interval: 5000, delay: 30000 },
                    { type: 'SHAHAB_3', count: 3, interval: 15000, delay: 35000 }
                ]
            }
        ];
        
        return waveConfigs.find(wave => wave.waveNumber === waveNumber) || null;
    }

    // 立即发射测试导弹
    public launchTestMissile(type: MissileType = 'FATEH_110'): void {
        const target = this.selectRandomTarget();
        this.launchMissile(type, target.x, target.y);
    }

    // 获取当前状态
    public getCurrentWave(): number {
        return this.currentWave;
    }

    public isWaveInProgress(): boolean {
        return this.isWaveActive;
    }

    public getActiveMissileCount(): number {
        return this.activeMissiles.length;
    }

    public getQueuedMissileCount(): number {
        return this.missileQueue.length;
    }

    public getTotalMissilesLaunched(): number {
        return this.totalMissilesLaunched;
    }

    public getActiveMissiles(): Missile[] {
        return [...this.activeMissiles];
    }

    // 强制结束当前波次
    public forceEndWave(): void {
        if (this.isWaveActive) {
            this.missileQueue = [];
            this.endCurrentWave();
        }
    }

    // 清理所有导弹
    public clearAllMissiles(): void {
        this.activeMissiles.forEach(missile => {
            missile.destroy();
            this.entitySystem.removeEntity(missile.id);
        });
        this.activeMissiles = [];
        this.missileQueue = [];
    }
}
